package com.baijiayun.live.ui.utils;

import android.app.Dialog;
import android.content.DialogInterface;
import android.view.ViewTreeObserver;

import com.baijia.bjydialog.MaterialDialog;

/**
 * Created by yongjiaming on 2020/4/3
 * Describe: 修复dialog设置监听导致Message持有activity
 * https://medium.com/square-corner-blog/a-small-leak-will-sink-a-great-ship-efbae00f9a0f
 */
public final class DetachableClickListener implements DialogInterface.OnClickListener, DialogInterface.OnShowListener {

    public static DetachableClickListener wrap(DialogInterface.OnClickListener delegate) {
        return new DetachableClickListener(delegate);
    }

    public static DetachableClickListener wrap(DialogInterface.OnShowListener delegate) {
        return new DetachableClickListener(delegate);
    }

    private DialogInterface.OnClickListener delegateOrNull;
    private DialogInterface.OnShowListener  delegateShowOrNull;
    private MaterialDialog.SingleButtonCallback delegateOfMD;

    private DetachableClickListener(DialogInterface.OnClickListener delegate) {
        this.delegateOrNull = delegate;
    }

    private DetachableClickListener(DialogInterface.OnShowListener delegate) {
        this.delegateShowOrNull = delegate;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (delegateOrNull != null) {
            delegateOrNull.onClick(dialog, which);
        }
    }

    @Override
    public void onShow(DialogInterface dialog) {
        if (delegateShowOrNull != null) {
            delegateShowOrNull.onShow(dialog);
        }
    }

    public void clearOnDetach(Dialog dialog) {
        dialog.getWindow()
                .getDecorView()
                .getViewTreeObserver()
                .addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListener() {
                    @Override
                    public void onWindowAttached() {
                    }

                    @Override
                    public void onWindowDetached() {
                        delegateOrNull = null;
                        delegateShowOrNull = null;
                    }
                });
    }
}